package high.concurent.config;

import feign.RequestInterceptor;
import high.concurrent.interceptor.UserInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;

/**
 * 配置拦截器生效，把拦截器注入spring
 */
@Configuration
@Slf4j
public class InterceptorConfig implements WebMvcConfigurer {

    /**
     * 实例化一下自定义的拦截器
     * @return
     */
    public UserInterceptor userInterceptor(){
        return new UserInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 声明指向哪一个拦截器
        registry.addInterceptor(userInterceptor())
                // 配置要拦截哪些路径
                .addPathPatterns("/api/user/*/**", "/api/address/*/**")
                // 配置放行哪些路径
                .excludePathPatterns("/api/user/*/uploadUserImg", "/api/user/*/registry", "/api/user/*/login");
    }

    /**
     * feign拦截器，防止feign内部调用token丢失（就写这一个就可以做到feign携带token）
     * 注意：RequestInterceptor要导入feign的
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){


        return requestTemplate -> {


            // 获取客户传过来的token
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes != null) {

                HttpServletRequest request = servletRequestAttributes.getRequest();
                if (request == null) {
                    return;
                }
                // 获取到前端token，并赋值到feign的token中
                String token = request.getHeader("token");
                requestTemplate.header("token", token);
            }
        };
    }
}
